<script setup lang="ts">
import { ref } from "vue";
import {
  IconPlay,
  IconHeart,
  IconHeartFilled,
  IconMusic,
  IconPlus,
} from "@/components/icons";
import { usePlayerStore } from "@/stores/player";
import { useUserStore } from "@/stores/user";
import { usePlaylistStore } from "@/stores/playlist";
import { useSongAPI } from "@/services/song";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const playerStore = usePlayerStore();
const userStore = useUserStore();
const playlistStore = usePlaylistStore();
const songAPI = useSongAPI();
const router = useRouter();

const props = defineProps<{
  songs: Array<any>;
  showHeader?: boolean;
}>();

const playSong = (song: any) => {
  console.log(song);

  playerStore.playSong(song, props.songs);
};

const handleCollect = async (song: any) => {
  if (!userStore.isLogin) {
    ElMessage.warning("请先登录");
    return;
  }

  const originalState = song.isFavorite;
  song.isFavorite = !originalState;

  try {
    const res = originalState
      ? await songAPI.getCancelCollectSong(song.id, userStore.uid)
      : await songAPI.getCollectSong(song.id, userStore.uid);

    if (res.code === 200) {
      return;
    } else {
      // 如果接口返回失败，回滚状态
      song.isFavorite = originalState;
      ElMessage.error(originalState ? "取消收藏失败" : "收藏失败");
    }
  } catch (error) {
    // 如果接口调用出错，回滚状态
    song.isFavorite = originalState;
    ElMessage.error(originalState ? "取消收藏失败" : "收藏失败");
    console.error("操作失败:", error);
  }
};

const formatDuration = (duration: string): string => {
  return duration?.substring(0, 5) || "00:00";
};

const addToPlaylist = async (song: any, playlistId: string) => {
  try {
    // TODO: 调用添加歌曲到歌单的 API
    console.log(song);

    const res = await songAPI.addSongToPlaylist(song.id, playlistId);
    if (res) {
      ElMessage.success("添加成功");
    } else {
      ElMessage.error("添加失败");
    }
  } catch (error) {
    ElMessage.error("添加失败");
    console.error("添加歌曲到歌单失败:", error);
  }
};

const goToSongDetail = (songId: number) => {
  router.push(`/song/${songId}`);
};
</script>

<template>
  <el-table :data="songs" style="width: 100%" :show-header="showHeader">
    <el-table-column width="60">
      <template #default="{ row }">
        <div
          class="w-8 h-8 flex justify-center items-center text-gray-400 hover:text-[#ec4141] border rounded-full hover:border-[#ec4141]"
          @click="playSong(row)"
        >
          <IconPlay class="w-5 h-5" />
        </div>
      </template>
    </el-table-column>

    <el-table-column width="80">
      <template #default="{ row }">
        <div
          class="w-12 h-12 rounded overflow-hidden bg-gray-100 flex items-center justify-center"
        >
          <template v-if="row.cover || row.musicCoverUrl">
            <img
              :src="row.cover || row.musicCoverUrl"
              :alt="row.name || row.musicName"
              class="w-full h-full object-cover"
            />
          </template>
          <template v-else>
            <IconMusic class="w-6 h-6 text-gray-400" />
          </template>
        </div>
      </template>
    </el-table-column>

    <el-table-column width="60">
      <template #default="{ row }">
        <button
          class="w-8 flex items-center justify-center"
          @click="handleCollect(row)"
        >
          <component
            :is="row.isFavorite ? IconHeartFilled : IconHeart"
            class="w-5 h-5"
            :class="{
              'text-[#ec4141]': row.isFavorite,
              'text-gray-500 hover:text-[#ec4141]': !row.isFavorite,
            }"
          />
        </button>
      </template>
    </el-table-column>

    <el-table-column width="60">
      <template #default="{ row }">
        <el-popover
          placement="right"
          :width="200"
          trigger="click"
          popper-class="playlist-popover"
        >
          <template #reference>
            <button
              class="w-8 h-8 flex items-center justify-center text-gray-400 hover:text-[#ec4141]"
            >
              <IconPlus class="w-5 h-5" />
            </button>
          </template>
          <div class="py-2">
            <h3 class="text-sm font-medium text-gray-900 px-3 mb-2">
              添加到歌单
            </h3>
            <template v-if="userStore.isLogin">
              <div
                v-for="playlist in playlistStore.userPlaylists"
                :key="playlist.id"
                class="px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer"
                @click="addToPlaylist(row, playlist.id)"
              >
                {{ playlist.name }}
              </div>
            </template>
            <div v-else class="px-3 py-2 text-sm text-gray-500">请先登录</div>
          </div>
        </el-popover>
      </template>
    </el-table-column>

    <el-table-column>
      <template #default="{ row }">
        <h3
          class="font-medium text-gray-900 hover:underline cursor-pointer"
          @click="goToSongDetail(row.id)"
        >
          {{ row.name || row.musicName }}
        </h3>
      </template>
    </el-table-column>

    <el-table-column>
      <template #default="{ row }">
        <div class="text-gray-500">
          {{ row.artist || row.musicAuthor }}
        </div>
      </template>
    </el-table-column>

    <el-table-column width="100" align="right">
      <template #default="{ row }">
        <div class="text-gray-500">
          {{ formatDuration(row.length || row.musicLength) }}
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped>
:deep(.el-table) {
  --el-table-border-color: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-hover-bg-color: #f9fafb;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__cell) {
  border-bottom: none;
}

:deep(.el-table__row) {
  border-radius: 8px;
}

:deep(.playlist-popover) {
  padding: 0;
  --el-popover-padding: 0;
}
</style>
